//https://leetcode.cn/problems/remove-duplicates-from-sorted-list-ii/



class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        if (head == nullptr || head->next == nullptr) return head;
        ListNode* phead = nullptr;
        ListNode* node = nullptr;
        ListNode* slow = head;
        ListNode* fast = head->next;
        while (fast) 
        {
            if (fast->val != slow->val) 
            {
                node = new ListNode(slow->val);
                if (phead == nullptr) 
                {
                    phead = node;
                } 
                else 
                {
                    ListNode* temp = phead;
                    while (temp->next) 
                    {
                        temp = temp->next;
                    }
                    temp->next = node;
                }
                slow = fast;
                fast = fast->next;
            } 
            else 
            {
                fast = fast->next;
                while (fast && fast->val == slow->val) 
                {
                    fast = fast->next;
                }
                slow = fast;
                if (fast) fast = fast->next;
            }
        }
        ListNode* prev = head;
        head = head->next;
        while(head)
        {
            if(head->next == nullptr)
            {
                if(head->val != prev->val)
                {
                    node = new ListNode(head->val);
                    if (phead == nullptr) 
                    {
                        phead = node;
                    } 
                    else 
                    {
                        ListNode* temp = phead;
                        while (temp->next) 
                        {
                            temp = temp->next;
                        }
                        temp->next = node;
                    }
                }
            }
            prev= head;
            head = head->next;
        }
        return phead;
    }
};



